﻿using System;
using System.Linq;

namespace CustomerContactSystem.WebForms.Enquiries.Comments {
    public partial class Edit : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id,commentid")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];
            GetComment();
        }

        private void GetComment() {
            SendToFixYourStreetCaption.Visible = false;
            SendToFixYourStreet.Visible = false;
            CompletesCommitmentCaption.Visible = false;
            CompletesCommitment.Visible = false;

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            var commentId = int.Parse(Request.QueryString["commentid"]);
            var comment = enquiry.Comments.SingleOrDefault(c => c.Id == commentId);

            if (comment == null) {
                return;
            }

            if (enquiry.CommitmentClosure != null && !enquiry.CommitmentClosure.Completed) {
                CompletesCommitmentCaption.Visible = true;
                CompletesCommitment.Visible = true;
            }

            if (enquiry.FixYourStreetId > 0 && !comment.SentToFixYourStreet) {
                SendToFixYourStreetCaption.Visible = true;
                SendToFixYourStreet.Visible = true;
            }

            if (enquiry.FixYourStreetId > 0 && comment.SentToFixYourStreet) {
                CommentDetailCaption.Visible = false;
                CommentDetail.Visible = false;
                return;
            }

            CommentDetail.Text = comment.Comment;
        }

        protected void SubmitCommentClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id,commentid")) {
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            var commentId = int.Parse(Request.QueryString["commentid"]);
            var comment = enquiry.UpdateComment(LoggedUser.DisplayName, commentId, CommentDetail.Text,
                                                SendToFixYourStreet.Checked, CompletesCommitment.Checked);

            if (!IsValidObject(comment, SubmitCommentResultMessage)) {
                return;
            }

            EnquiryRepository.Update(enquiry);
            Response.Redirect("~/Enquiries/View.aspx?id=" + comment.Enquiry.Id);
        }
    }
}